
/**
 * 格式整理，输出YYYY-MM-DD格式的日期
 */
const formatDay = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  return [year, month, day].map(formatNumber).join('-')
}

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const gotop = () => {
  if (wx.pageScrollTo) {
    wx.pageScrollTo({
      scrollTop: 0
    })
  } else {
    wx.showModal({
      title: '提示',
      content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
    })
  }
}

/* 
手机号码检测 
传入参数
  phoneNum：手机号
*/
const phoneNumberVerification = (phoneNum) => {
  var reg = /^0?1[3|4|5|7|8][0-9]\d{8}$/;
  if (reg.test(phoneNum)) {
    return true;
  } else {
    return false;
  }
}

/**
 * 对微信API添加的异步解决方法
 */
const wxPromisify = (fn) => {
  return function (obj = {}) {
    return new Promise((resolve, reject) => {
      obj.success = function (res) {
        resolve(res)
      }
      obj.fail = function (res) {
        reject(res)
      }
      fn(obj)
    })
  }
}

/**
 * 获取时间戳
 */
const getTimeStamp = () => {
  return (new Date()).valueOf();
}

/**
 * 请求中的数据格式转换
 */
const jsonForm = (json) => {
  var str = [];
  for (var p in json) {
    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]));
  }
  return str.join("&");
}

/**
 * 判断空值
 */
const isEmpty = (value) => {
  if (value === "" || value === undefined || value === null || value.length === 0 || value === "null") {
    return true;
  } else {
    return false;
  }
}

export {
  formatDay,
  formatTime,
  gotop,
  jsonForm,
  phoneNumberVerification,
  getTimeStamp,
  isEmpty
}
